<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 12.1</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="12.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="12.1.1.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P2">Part II. Tables and Objects</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#12">Chapter 12. Data Files and Persistence</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>12.1 &ndash; Serialization</h2>

<p>

<p>Frequently we need to serialize some data,
that is, to convert the data into a stream of bytes or characters,
so that we can save it into a file or send it through a network
connection.
We can represent serialized data as Lua code,
in such a way that, when we run the code,
it reconstructs the saved values into the reading program.

<p>Usually, if we want to restore the value of a global variable,
our chunk will be something like <code>varname = &lt;exp></code>,
where <code>&lt;exp></code> is the Lua code to create the value.
The <code>varname</code> is the easy part,
so let us see how to write the code that creates a value.
For a numeric value, the task is easy:
<pre>
    function serialize (o)
      if type(o) == "number" then
        io.write(o)
      else ...
    end
</pre>
For a string value,
a naive approach would be something like
<pre>
    if type(o) == "string" then
      io.write("'", o, "'")
</pre>
However, if the string contains special characters
(such as quotes or newlines)
the resulting code will not be a valid Lua program.
Here, you may be tempted to solve this problem changing quotes:
<pre>
    if type(o) == "string" then
      io.write("[[", o, "]]")
</pre>
Do not do that!
Double square brackets are intended for hand-written strings,
not for automatically generated ones.
If a malicious user manages to direct your
program to save something like
<code>" ]]..os.execute('rm *')..[[ "</code>
(for instance, she can supply that string as her address),
your final chunk will be
<pre>
    varname = [[ ]]..os.execute('rm *')..[[ ]]
</pre>
You will have a bad surprise trying to load this "data".

<p>To quote an arbitrary string in a secure way,
the <code>format</code> function, from the standard <code>string</code> library,
offers the option <code>"%q"</code>.
It surrounds the string with double quotes
and properly escapes double quotes, newlines,
and some other characters inside the string.
Using this feature, our <code>serialize</code> function now looks like this:
<pre>
    function serialize (o)
      if type(o) == "number" then
        io.write(o)
      elseif type(o) == "string" then
        io.write(string.format("%q", o))
      else ...
    end
</pre>

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="12.1.1.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

